<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="批次号" prop="ryTaskId">
              <el-input v-model="queryParams.ryTaskId" placeholder="请输入批次号" clearable />
            </el-form-item>
            <el-form-item label="子ASIN" prop="fnSku">
              <el-input v-model="queryParams.fnSku" placeholder="请输入" clearable />
            </el-form-item>
            <!-- <el-form-item label="物料" prop="materialId">
              <el-selectDialog
                v-model="queryParams.materialId"
                filterable
                :filter-method="filterTask"
                placeholder="请选择物料"
                clearable
                :disabled="dialog.title === '修改产品'"
              >
                <el-option
                  v-for="item in materialList"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId"
                ></el-option>
              </el-selectDialog>
            </el-form-item> -->

            <!-- <el-form-item label="任务id" prop="ryTaskId">
              <el-input
                v-model="queryParams.ryTaskId"
                placeholder="请输入任务id"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleStat">批量提交采购试算</el-button>-->
          <!--          </el-col>-->

          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleStatAll">汇总下单</el-button>
          </el-col>
          <el-text style="color: red"
            >数据来源：运营优化链接，审批通过之后生成的记录。 等所有运营提交完计划后，点击汇总，按照通用码汇总生成汇总记录</el-text
          >

          <!-- <el-col :span="1.5">
            <el-button
              v-hasPermi="['oa:restockingPlan:add']"
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['oa:restockingPlan:edit']"
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate()"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['oa:restockingPlan:remove']"
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermi="['oa:restockingPlan:export']"
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
            >导出</el-button>
          </el-col> -->
        </el-row>
        <!--        <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>-->
      </template>

      <el-table v-loading="loading" :data="restockingPlanList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <el-table-column label="批次号" align="center" prop="ryTaskId" width="180" />
        <el-table-column label="运营负责人" align="center" prop="principalRealname" />
        <el-table-column label="子ASIN" align="center" prop="fnSku" width="180" />
        <el-table-column label="月份" align="center" prop="month">
          <template #default="scope">{{ formatMonth(scope.row.month) }}</template>
        </el-table-column>
        <el-table-column label="亚马逊在途" align="center" prop="fbaOnTheWay" />
        <el-table-column label="亚马逊可售" align="center" prop="fbaSellable" />
        <el-table-column label="仓库库存" align="center" prop="domesticWarehouseInventory" />
        <el-table-column label="总库存" align="center" prop="totalInventory" />
        <el-table-column label="预估日销" align="center" prop="expectedDaySale" />
        <el-table-column label="库存缺口" align="center" prop="inventoryShortfall" />
        <el-table-column label="缺口天数" align="center" prop="gapDays" />
        <el-table-column label="当前可售天数" align="center" prop="currentSaleTodayNum" />
        <el-table-column label="安全库存预留数量" align="center" prop="reserveSafetyStockNum" />
        <el-table-column label="总需求" align="center" prop="aggregateDemand" />

        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            {{ restocking_plan_status.find((item) => Number(item.value) === scope.row.status)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['oa:restockingPlan:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['oa:restockingPlan:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改补货计划对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="restockingPlanFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="fnSku" prop="fnSku" label-width="100">
              <el-input v-model="form.fnSku" placeholder="请输入fnSku" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="亚马逊在途" prop="fbaOnTheWay" label-width="130">
              <el-input v-model="form.fbaOnTheWay" placeholder="请输入亚马逊在途" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="亚马逊可售" prop="fbaSellable" label-width="130">
              <el-input v-model="form.fbaSellable" placeholder="请输入亚马逊可售" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="其他可售" prop="otherSellable" label-width="130">
              <el-input v-model="form.otherSellable" placeholder="请输入其他可售" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="海外仓库库存" prop="overseasWarehouseInventory" label-width="130">
              <el-input v-model="form.overseasWarehouseInventory" placeholder="请输入海外仓库库存" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="国内仓库库存" prop="domesticWarehouseInventory" label-width="130">
              <el-input v-model="form.domesticWarehouseInventory" placeholder="请输入国内仓库库存" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="总库存" prop="totalInventory" label-width="130">
              <el-input v-model="form.totalInventory" placeholder="请输入总库存" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="月份" prop="month" label-width="150">
              <el-input v-model="form.month" placeholder="请输入月份string" :disabled="dialog.title === '修改补货计划'" />
            </el-form-item>
            <el-form-item label="库存缺口" prop="inventoryShortfall" label-width="150">
              <el-input v-model="form.inventoryShortfall" placeholder="请输入库存缺口" />
            </el-form-item>
            <el-form-item label="缺口天数" prop="gapDays" label-width="150">
              <el-input v-model="form.gapDays" placeholder="请输入缺口天数" />
            </el-form-item>
            <el-form-item label="当前可售天数" prop="currentSaleTodayNum" label-width="150">
              <el-input v-model="form.currentSaleTodayNum" placeholder="请输入当前可售天数" />
            </el-form-item>
            <el-form-item label="安全库存预留数量" prop="reserveSafetyStockNum" label-width="150">
              <el-input v-model="form.reserveSafetyStockNum" placeholder="请输入安全库存预留数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark" label-width="130">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RestockingPlan" lang="ts">
import { list } from '@/api/material/material';
import {
  listRestockingPlan,
  getRestockingPlan,
  delRestockingPlan,
  addRestockingPlan,
  updateRestockingPlan,
  statAll
} from '@/api/plan/restockingPlan';
import { RestockingPlanVO, RestockingPlanQuery, RestockingPlanForm } from '@/api/plan/restockingPlan/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { restocking_plan_status } = toRefs<any>(proxy?.useDict('restocking_plan_status'));

const restockingPlanList = ref<RestockingPlanVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const materialList = ref([]);
const backupList = ref([]);

const queryFormRef = ref<ElFormInstance>();
const restockingPlanFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: RestockingPlanForm = {
  id: undefined,
  fnSku: undefined,
  materialId: undefined,
  monthData: undefined,
  fbaOnTheWay: undefined,
  otherOnTheWay: undefined,
  fbaSellable: undefined,
  otherSellable: undefined,
  overseasWarehouseInventory: undefined,
  domesticWarehouseInventory: undefined,
  supplierInventory: undefined,
  ryTaskId: undefined,
  status: undefined,
  remark: undefined,
  totalInventory: undefined,
  inventoryShortfall: undefined,
  gapDays: undefined,
  currentSaleTodayNum: undefined,
  reserveSafetyStockNum: undefined,
  enclosure: undefined,
  aggregateDemand: undefined,
  deptId: undefined,
  errorMsg: undefined
};
const data = reactive<PageData<RestockingPlanForm, RestockingPlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    fnSku: undefined,
    materialId: undefined,
    monthData: undefined,
    fbaOnTheWay: undefined,
    otherOnTheWay: undefined,
    fbaSellable: undefined,
    otherSellable: undefined,
    overseasWarehouseInventory: undefined,
    domesticWarehouseInventory: undefined,
    supplierInventory: undefined,
    ryTaskId: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    // fnSku: [{ required: true, message: '不能为空', trigger: 'blur' }],
    // materialId: [{ required: true, message: '物料id不能为空', trigger: 'blur' }],
    // monthData: [{ required: true, message: '月份数量不能为空', trigger: 'blur' }],
    // fbaOnTheWay: [{ required: true, message: '亚马逊_在途不能为空', trigger: 'blur' }],
    // otherOnTheWay: [{ required: true, message: '其他_在途不能为空', trigger: 'blur' }],
    // fbaSellable: [{ required: true, message: '亚马逊可售不能为空', trigger: 'blur' }],
    // otherSellable: [{ required: true, message: '其他可售不能为空', trigger: 'blur' }],
    // overseasWarehouseInventory: [{ required: true, message: '海外仓库库存不能为空', trigger: 'blur' }],
    // domesticWarehouseInventory: [{ required: true, message: '国内仓库库存不能为空', trigger: 'blur' }],
    // supplierInventory: [{ required: true, message: '供应商库存不能为空', trigger: 'blur' }],
    // status: [{ required: true, message: '状态[0草稿，1发布]不能为空', trigger: 'change' }],
    // remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
    inventoryShortfall: [{ required: true, message: '库存缺口不能为空', trigger: 'blur' }],
    gapDays: [{ required: true, message: '缺口天数不能为空', trigger: 'blur' }],
    currentSaleTodayNum: [{ required: true, message: '当前可售天数不能为空', trigger: 'blur' }],
    reserveSafetyStockNum: [{ required: true, message: '安全库存预留数量不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const filterTask = (query: string) => {
  if (query) {
    const filtered = materialList.value.filter((item) => {
      return item.materialName.includes(query);
    });
    materialList.value = filtered.length > 0 ? filtered : [];
  } else {
    materialList.value = backupList.value;
  }
};

const getMaterialList = async () => {
  loading.value = true;
  const res = await list({ materialType: '0' });
  materialList.value = res.data;
  backupList.value = res.data;
  loading.value = false;
};

/** 查询补货计划列表 */
const getList = async () => {
  loading.value = true;
  const res = await listRestockingPlan(queryParams.value);
  restockingPlanList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  restockingPlanFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: RestockingPlanVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加补货计划';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RestockingPlanVO) => {
  reset();
  console.log(row);
  const _id = row?.id || ids.value[0];
  const res = await getRestockingPlan(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改补货计划';
};

/** 提交按钮 */
const submitForm = () => {
  restockingPlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateRestockingPlan(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addRestockingPlan(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: RestockingPlanVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除补货计划编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delRestockingPlan(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/restockingPlan/export',
    {
      ...queryParams.value
    },
    `restockingPlan_${new Date().getTime()}.xlsx`
  );
};

// const handleStat = async () => {
//   if (!ids.value) {
//     proxy?.$modal.alertWarning('请选择数据!!!');
//     return;
//   }
//   loading.value = true;
//   await proxy?.$modal.confirm('是否提交采购试算？').finally(() => (loading.value = false));
//   loading.value = true;
//   await handleStat(ids.value).finally(() => (loading.value = false));
//   proxy?.$modal.msgSuccess('同步数据成功!');
//   loading.value = true;
//   await getList().finally(() => (loading.value = false));
// };
//
const handleStatAll = async () => {
  loading.value = true;
  await proxy?.$modal.confirm('是否提交汇总下单？').finally(() => (loading.value = false));
  loading.value = true;
  await statAll().finally(() => (loading.value = false));
  proxy?.$modal.msgSuccess('操作成功!');
  loading.value = true;
  await getList().finally(() => (loading.value = false));
};

const formatMonth = (monthString) => {
  // 同步处理字符串
  return monthString.replace(/[\[\]"]/g, '').replace(/,\s+/g, ',');
};

onMounted(() => {
  getList();
  getMaterialList();
});
</script>
